﻿using NewsReader.Log;
using NewsReader.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Foundation;

namespace NewsReader.Parsers
{
    internal class Readibility : Parser
    {
        public override string GetFormattedArticle(Uri originalUri)
        {
            string serviceUri = string.Concat(UriBase, WebUtility.UrlEncode(originalUri.AbsoluteUri));
            using (var req = new HttpClient())
            {
                try
                {
                    var message = new HttpRequestMessage(HttpMethod.Get, serviceUri);
                    if (!string.IsNullOrEmpty(UserAgent))
                    {
                        message.Headers.Add("User-Agent", UserAgent);
                    }
                    var response = req.SendAsync(message).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
                catch (Exception ex)
                {
                    Logger.Log.ErrorFormat("Getting formatted article error: {0}", ex);
                    throw;
                }
            }
        }

        public override string Parse(string fullText)
        {
            JsonObject obj;
            if (JsonObject.TryParse(fullText, out obj))
            {
                IJsonValue value;
                if (obj.TryGetValue("content", out value))
                {
                    return value.GetString();
                }
                else
                {
                    if (obj.TryGetValue("error", out value) && value.GetBoolean() && obj.TryGetValue("messages", out value))
                    {
                        return FeedItem.ERROR_STRING;
                    }
                }
            }

            return null;
        }
    }
}
